/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.rest;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.business.domain.PricRegn;
import me.zhengjie.business.service.PricRegnService;
import me.zhengjie.business.service.dto.PricRegnDto;
import me.zhengjie.business.service.dto.PricRegnQueryCriteria;
import me.zhengjie.business.util.HttpNewMicProvince;
import me.zhengjie.business.util.SmUtilProvince;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.nmi.ChsInterfaceConfig;
import me.zhengjie.nmi.ChsUtil;
import me.zhengjie.utils.DateTimeUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author xiahongbo
* @date 2025-01-02
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "照护区管理")
@RequestMapping("/api/pricRegn")
public class PricRegnController {

    private final PricRegnService pricRegnService;

    private final DeptService deptService;

    private final HttpNewMicProvince httpNewMicProvince;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('pricRegn:list')")
    public void exportPricRegn(HttpServletResponse response, PricRegnQueryCriteria criteria) throws IOException {
        pricRegnService.download(pricRegnService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询照护区")
    @ApiOperation("查询照护区")
    @PreAuthorize("@el.check('pricRegn:list','pricBed:list')")
    public ResponseEntity<Object> queryPricRegn(PricRegnQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(pricRegnService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增照护区")
    @ApiOperation("新增照护区")
    @PreAuthorize("@el.check('pricRegn:add')")
    public ResponseEntity<Object> createPricRegn(@Validated @RequestBody PricRegn resources) {
        String bcn = DateTimeUtil.getDateTime("yyyyMMddHHmmss")+ (int) ((Math.random() * 9 + 1) * 1000);
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        cn.hutool.json.JSONObject userJson = new cn.hutool.json.JSONObject(new cn.hutool.json.JSONObject(userDetails).get("user"));
        cn.hutool.json.JSONObject deptJson = new cn.hutool.json.JSONObject(userJson.get("dept"));
        log.info("sign deptJson:{}", deptJson);

        Long userId = SecurityUtils.getCurrentUserId();
        String nickName = SecurityUtils.getCurrentNickName();
        String username = SecurityUtils.getCurrentUsername();
        Long deptId = Long.parseLong(deptJson.getStr("id"));
        DeptDto deptDto = deptService.findById(deptId);



        String datetime = DateTimeUtil.getDateTime();
        String nurscare_regn_no = deptId+"_"+bcn;

        resources.setNurscareOrgNo(deptDto.getDeptCode());
        resources.setNurscareOrgId(deptDto.getOrgId());
        resources.setNurscareRegnNo(nurscare_regn_no);
        resources.setRid(IdUtil.simpleUUID());

        resources.setCrtetime(DateTimeUtil.getNow());
        resources.setUpdttime(DateTimeUtil.getNow());
        resources.setCrterid(String.valueOf(userId));
        resources.setCrtername(nickName);
        resources.setCrteoptinsno(deptDto.getDeptCode());

        resources.setOpterid(String.valueOf(userId));
        resources.setOptername(nickName);
        resources.setOptinsno(deptDto.getDeptCode());
        resources.setOpttime(DateTimeUtil.getNow());
        // 有效标志
        resources.setValiflag("1");

        String input = "{\"data\": {" +
                "\"nurscare_org_no\":\""+resources.getNurscareOrgNo()+"\"," +
                "\"nurscare_org_id\":\""+resources.getNurscareOrgId()+"\"," +
                "\"nurscare_regn_no\":\""+resources.getNurscareRegnNo()+"\"," +
                "\"nurscare_regn_name\":\""+resources.getNurscareRegnName()+"\"," +
                "\"nurscare_regn_type\":\""+resources.getNurscareRegnType()+"\"," +
                "\"room_cnt\":\""+resources.getRoomCnt()+"\"," +
                "\"bed_val\":\""+resources.getBedVal()+"\"," +
                "\"nurscare_psn_cnt\":\""+resources.getNurscarePsnCnt()+"\"," +
                "\"dscr\":\""+resources.getDscr()+"\"," +
                "\"rid\":\""+resources.getRid()+"\"," +
                "\"crteTime\":\""+datetime+"\"," +
                "\"updtTime\":\""+datetime+"\"," +
                "\"crterId\":\""+resources.getCrterid()+"\"," +
                "\"crterName\":\""+resources.getCrtername()+"\"," +
                "\"crteOptinsNo\":\""+resources.getCrteoptinsno()+"\"," +
                "\"opterId\":\""+resources.getOpterid()+"\"," +
                "\"opterName\":\""+resources.getOptername()+"\"," +
                "\"optTime\":\""+datetime+"\"," +
                "\"optinsNo\": \""+resources.getOptinsno()+"\"," +
                "\"admdvs\": \"\"," +
                "\"valiFlag\": \""+resources.getValiflag()+"\"," +
                "\"dataVer\": \"\"}}";
        //签名
        String sign = SmUtilProvince.sign(input, deptDto);
        //加密
        String sm4Input = SmUtilProvince.encrypt(input, deptDto);

        String message = "{\"infno\": \"8902\"," +
                "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                "\"insuplc_admdvs\": \"\"," +
                "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                "\"dev_no\": \"\"," +
                "\"dev_safe_info\": \"\"," +
                "\"cainfo\": \"" + sign + "\"," +
                "\"signtype\": \"SM2\"," +
                "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                "\"opter_type\": \"1\"," +
                "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                "\"sign_no\": \"" + bcn + "\"," +
                "\"input\": \"" + sm4Input + "\"}";

        String encryptResult = httpNewMicProvince.handle(message, "机构新增照护区", deptDto);
        JSONObject result = JSONObject.parseObject(encryptResult);
        if ("0".equals(result.getString("infcode"))) {
            String decryptionResult = SmUtilProvince.decryption(result.getString("output"), deptDto);

            String input8901 = "{\"data\": {" +
                    "\"nurscare_org_no\":\""+deptDto.getDeptCode()+"\"," +
                    "\"nurscare_org_id\": \"\"," +
                    "\"nurscare_regn_no\": \""+resources.getNurscareRegnNo()+"\"," +
                    "\"nurscare_regn_name\": \"\"," +
                    "\"nurscare_regn_type\": \"\"," +
                    "\"pageNum\": \"1\"," +
                    "\"pageSize\": \"100\"," +
                    "\"admdvs\": \"\"}}";
            //签名
            String sign8901 = SmUtilProvince.sign(input8901, deptDto);
            //加密
            String sm4Input8901 = SmUtilProvince.encrypt(input8901, deptDto);

            String message8901 = "{\"infno\": \"8901\"," +
                    "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                    "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                    "\"insuplc_admdvs\": \"\"," +
                    "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                    "\"dev_no\": \"\"," +
                    "\"dev_safe_info\": \"\"," +
                    "\"cainfo\": \"" + sign8901 + "\"," +
                    "\"signtype\": \"SM2\"," +
                    "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                    "\"opter_type\": \"1\"," +
                    "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                    "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                    "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                    "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                    "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                    "\"sign_no\": \"" + bcn + "\"," +
                    "\"input\": \"" + sm4Input8901 + "\"}";

            String encryptResult8901 = httpNewMicProvince.handle(message8901, "查询机构照护区", deptDto);
            JSONObject result8901 = JSONObject.parseObject(encryptResult8901);
            if ("0".equals(result8901.getString("infcode"))) {

                String decryptionResult8901 = SmUtilProvince.decryption(result8901.getString("output"), deptDto);
                JSONObject output8901 = JSONObject.parseObject(decryptionResult8901);
                JSONArray dataArray8901 = output8901.getJSONArray("data");
                JSONObject regnObject = dataArray8901.getJSONObject(0);
                String longterm_org_nurscare_regn_id = regnObject.getString("longterm_org_nurscare_regn_id");

                resources.setLongtermOrgNurscareRegnId(longterm_org_nurscare_regn_id);
                return new ResponseEntity<>(pricRegnService.create(resources),HttpStatus.CREATED);
            } else {
                return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
            }


        } else {
            //return AjaxResult.error(result.getString("err_msg"));
            return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
        }

    }

    @PutMapping
    @Log("修改照护区")
    @ApiOperation("修改照护区")
    @PreAuthorize("@el.check('pricRegn:edit')")
    public ResponseEntity<Object> updatePricRegn(@Validated @RequestBody PricRegn resources){

        log.info("updatePricRegn - resources:{}", resources);
        String bcn = DateTimeUtil.getDateTime("yyyyMMddHHmmss")+ (int) ((Math.random() * 9 + 1) * 1000);
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        cn.hutool.json.JSONObject userJson = new cn.hutool.json.JSONObject(new cn.hutool.json.JSONObject(userDetails).get("user"));
        cn.hutool.json.JSONObject deptJson = new cn.hutool.json.JSONObject(userJson.get("dept"));
        log.info("sign deptJson:{}", deptJson);

        Long userId = SecurityUtils.getCurrentUserId();
        String nickName = SecurityUtils.getCurrentNickName();
        String username = SecurityUtils.getCurrentUsername();
        Long deptId = Long.parseLong(deptJson.getStr("id"));
        DeptDto deptDto = deptService.findById(deptId);


        String input = "{\"data\": {" +
                "\"nurscare_org_no\":\""+resources.getNurscareOrgNo()+"\"," +
                "\"nurscare_org_id\":\""+resources.getNurscareOrgId()+"\"," +
                "\"nurscare_regn_no\":\""+resources.getNurscareRegnNo()+"\"," +
                "\"longterm_org_nurscare_regn_id\":\""+resources.getLongtermOrgNurscareRegnId()+"\"," +
                "\"nurscare_regn_name\":\""+resources.getNurscareRegnName()+"\"," +
                "\"nurscare_regn_type\":\""+resources.getNurscareRegnType()+"\"," +
                "\"room_cnt\":\""+resources.getRoomCnt()+"\"," +
                "\"bed_val\":\""+resources.getBedVal()+"\"," +
                "\"nurscare_psn_cnt\":\""+resources.getNurscarePsnCnt()+"\"," +
                "\"dscr\":\""+resources.getDscr()+"\"," +
                "\"rid\":\""+resources.getRid()+"\"," +
                "\"admdvs\": \"\"," +
                "\"valiFlag\": \""+resources.getValiflag()+"\"," +
                "\"dataVer\": \"\"}}";
        log.info("updatePricRegn - input:{}", input);
        //签名
        String sign = SmUtilProvince.sign(input, deptDto);
        //加密
        String sm4Input = SmUtilProvince.encrypt(input, deptDto);

        String message = "{\"infno\": \"8903\"," +
                "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                "\"insuplc_admdvs\": \"\"," +
                "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                "\"dev_no\": \"\"," +
                "\"dev_safe_info\": \"\"," +
                "\"cainfo\": \"" + sign + "\"," +
                "\"signtype\": \"SM2\"," +
                "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                "\"opter_type\": \"1\"," +
                "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                "\"sign_no\": \"" + bcn + "\"," +
                "\"input\": \"" + sm4Input + "\"}";

        String encryptResult = httpNewMicProvince.handle(message, "修改机构照护区信息", deptDto);
        log.info("updatePricRegn - encryptResult:{}", encryptResult);
        JSONObject result = JSONObject.parseObject(encryptResult);
        if ("0".equals(result.getString("infcode"))) {
            String decryptionResult = SmUtilProvince.decryption(result.getString("output"), deptDto);

            pricRegnService.update(resources);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } else {
            //return AjaxResult.error(result.getString("err_msg"));
            return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
        }

/*
        pricRegnService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);*/

    }

    @DeleteMapping
    @Log("删除照护区")
    @ApiOperation("删除照护区")
    @PreAuthorize("@el.check('pricRegn:del')")
    public ResponseEntity<Object> deletePricRegn(@RequestBody String[] ids) {

        PricRegnDto resources = pricRegnService.findById(ids[0]);
        log.info("deletePricRegn - resources:{}", resources);

        String bcn = DateTimeUtil.getDateTime("yyyyMMddHHmmss")+ (int) ((Math.random() * 9 + 1) * 1000);
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        cn.hutool.json.JSONObject userJson = new cn.hutool.json.JSONObject(new cn.hutool.json.JSONObject(userDetails).get("user"));
        cn.hutool.json.JSONObject deptJson = new cn.hutool.json.JSONObject(userJson.get("dept"));
        log.info("sign deptJson:{}", deptJson);

        Long userId = SecurityUtils.getCurrentUserId();
        String nickName = SecurityUtils.getCurrentNickName();
        String username = SecurityUtils.getCurrentUsername();
        Long deptId = Long.parseLong(deptJson.getStr("id"));
        DeptDto deptDto = deptService.findById(deptId);


        String input = "{\"data\": {" +
                "\"nurscare_org_no\":\""+resources.getNurscareOrgNo()+"\"," +
                "\"nurscare_org_id\":\""+resources.getNurscareOrgId()+"\"," +
                "\"nurscare_regn_no\":\""+resources.getNurscareRegnNo()+"\"," +
                "\"longterm_org_nurscare_regn_id\": \""+resources.getLongtermOrgNurscareRegnId()+"\"}}";


        log.info("deletePricRegn - input:{}", input);
        //签名
        String sign = SmUtilProvince.sign(input, deptDto);
        //加密
        String sm4Input = SmUtilProvince.encrypt(input, deptDto);

        String message = "{\"infno\": \"8904\"," +
                "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                "\"insuplc_admdvs\": \"\"," +
                "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                "\"dev_no\": \"\"," +
                "\"dev_safe_info\": \"\"," +
                "\"cainfo\": \"" + sign + "\"," +
                "\"signtype\": \"SM2\"," +
                "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                "\"opter_type\": \"1\"," +
                "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                "\"sign_no\": \"" + bcn + "\"," +
                "\"input\": \"" + sm4Input + "\"}";

        String encryptResult = httpNewMicProvince.handle(message, "删除机构照护区", deptDto);
        log.info("deletePricRegn - encryptResult:{}", encryptResult);
        JSONObject result = JSONObject.parseObject(encryptResult);
        if ("0".equals(result.getString("infcode"))) {
            String decryptionResult = SmUtilProvince.decryption(result.getString("output"), deptDto);

            pricRegnService.deleteAll(ids);
            return new ResponseEntity<>(HttpStatus.OK);
        } else {
            //return AjaxResult.error(result.getString("err_msg"));
            return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
        }


    }
}